﻿using System;
using System.Globalization;
using ContractManagementSystem.BusinessLogicLayer;
using ContractManagementSystem.EntityObjects;

namespace ContractManagementSystem.Presentation.ProfileManagement
{
    public partial class ViewContractor : System.Web.UI.Page
    {
        private int _roleId;
        private string _userName;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["RoleId"] != null && Session["UserName"] != null)
            {
                _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
                CheckUserPermission();
                DisableTextBox();
                if (!IsPostBack)
                    LoadDataContractor();
            }
            else
            {
                Response.Redirect("../LogOn.aspx");
            }
        }

        private void LoadDataContractor()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
            _userName = Session["UserName"].ToString();
            if (_roleId==1 | _roleId==4 | _roleId==3)
            {
                ButtonEdit.Visible = false;
                ButtonSave.Visible = false;
                LoadUpdateContractor();
            }
            else if(_roleId==2)
            {
                ButtonEdit.Visible = true;
                ButtonSave.Visible = true;
                LoadContractorInfo();
            }
        }
        //load info detail  a contractor by role admin 
        private void LoadUpdateContractor()
        {
            var id = Request.QueryString["id"];
            if (!string.IsNullOrEmpty(id))
            {
                var dataTable = ContractorProfileLogic.GetContractorByContractorId(id);
                textId.Text = id;
                textUserName.Text = dataTable.Rows[0]["UserName"].ToString();
                textFullName.Text = dataTable.Rows[0]["FullName"].ToString();
                textPhoneNumber1.Text = dataTable.Rows[0]["PhoneNumber1"].ToString();
                textAddress.Text = dataTable.Rows[0]["Address"].ToString();
                textPhoneNumber2.Text = dataTable.Rows[0]["PhoneNumber2"].ToString();
                textEmail.Text = dataTable.Rows[0]["Email"].ToString();
                textBranch.Text = dataTable.Rows[0]["Branch"].ToString();
                textSortCode.Text = dataTable.Rows[0]["SortCode"].ToString();
            }
        }
        //load info contractor when singin by role contractor 
        protected void LoadContractorInfo()
        {
            var dataTable = ContractorProfileLogic.GetContractorByContractorUserName(_userName);
            if (dataTable != null)
            {
                textId.Text = dataTable.Rows[0]["Id"].ToString();
                textUserName.Text = dataTable.Rows[0]["UserName"].ToString();
                textFullName.Text = dataTable.Rows[0]["FullName"].ToString();
                textPhoneNumber1.Text = dataTable.Rows[0]["PhoneNumber1"].ToString();
                textAddress.Text = dataTable.Rows[0]["Address"].ToString();
                textPhoneNumber2.Text = dataTable.Rows[0]["PhoneNumber2"].ToString();
                textEmail.Text = dataTable.Rows[0]["Email"].ToString();
                textBranch.Text = dataTable.Rows[0]["Branch"].ToString();
                textSortCode.Text = dataTable.Rows[0]["SortCode"].ToString();
            }
        }
        // when load this page info client not edit 
        protected void DisableTextBox()
        {
            textId.Enabled = false;
            textUserName.Enabled = false;
            textFullName.Enabled = false;
            textPhoneNumber1.Enabled = false;
            textAddress.Enabled = false;
            textPhoneNumber2.Enabled = false;
            textEmail.Enabled = false;
            textBranch.Enabled = false;
            textSortCode.Enabled = false;
        }
        //when user click button edit enable textbox allow edit info
        protected void EnableTextBox()
        {
            textId.Enabled = false;
            textUserName.Enabled = false;
            textFullName.Enabled = false;
            textPhoneNumber1.Enabled = true;
            textPhoneNumber1.CssClass = "CPFInputField cpfdetailText";
            textAddress.Enabled = true;
            textAddress.CssClass = "CPFInputField cpfdetailText";
            textPhoneNumber2.Enabled = true;
            textPhoneNumber2.CssClass = "CPFInputField cpfdetailText";
            textEmail.Enabled = false;
            textBranch.Enabled = true;
            textBranch.CssClass = "CPFInputField cpfdetailText";
            textSortCode.Enabled = true;
            textSortCode.CssClass = "CPFInputField cpfdetailText";
        }

        protected void ButtonEditClick(object sender, EventArgs e)
        {
            EnableTextBox();
        }

        protected void ButtonSaveClick(object sender, EventArgs e)
        {
            var contractor = new ContractorEntity
                              {
                                  ContractorId = int.Parse((textId.Text), CultureInfo.InvariantCulture),
                                  UserName = textUserName.Text,
                                  FullName = textFullName.Text,
                                  Address = textAddress.Text,
                                  PhoneNumber1 = textPhoneNumber1.Text,
                                  PhoneNumber2 = textPhoneNumber2.Text,
                                  Email = textEmail.Text,
                                  Branch = textBranch.Text,
                                  SortCode = textSortCode.Text
                              };
            var result = ContractorProfileLogic.UpdateContractor(contractor);
            if (result == "Successfully!")
            {
                labelResult.Text = "Update information successfull!";
                DisableTextBox();
                var userEventEntity = new EventEntity
                                          {
                                              UserName = CommonLogic.ConvertToString(Session["UserName"]),
                                              EventType = (int) EventTypeList.UserEvent,
                                              OnDate = DateTime.Now,
                                              Description = "User update success"
                                          };
                EventTracer.SaveEvents(userEventEntity);               
            }
            else
            {
                var userEventEntity = new EventEntity
                                          {
                                              UserName = CommonLogic.ConvertToString(Session["UserName"]),
                                              EventType = (int) EventTypeList.UserEvent,
                                              OnDate = DateTime.Now,
                                              Description = "User update failed"
                                          };
                EventTracer.SaveEvents(userEventEntity);    
            }

        }
        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.ViewContractor;

            if (Page.Master != null)
            {
                var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

                AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
            }
        }
    }
}
